package com.icoolkj.ms.auth.service.impl;

import cn.hutool.core.util.StrUtil;
import com.icoolkj.ms.api.auth.dto.CaptchaDTO;
import com.icoolkj.ms.auth.service.IAuthStrategy;
import com.icoolkj.ms.common.cache.utils.RedisUtil;
import com.icoolkj.ms.common.core.constant.GlobalConstants;
import com.icoolkj.ms.common.core.exception.IcoolkjMSException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/02/24 10:51
 */
public abstract class AbstractAuthStrategy implements IAuthStrategy {

    protected static final Logger logger = LoggerFactory.getLogger(AbstractAuthStrategy.class);

    protected boolean doValidateCode(String keyField, String fieldName, CaptchaDTO captchaDTO) {
        if (StrUtil.isEmpty(keyField)) {
            logger.error("{}不能为空", fieldName);
            throw new IcoolkjMSException(fieldName + "不能为空");
        }
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StrUtil.blankToDefault(keyField, "");
        logger.info("尝试从 Redis 中获取验证码，键: {}", verifyKey);
        String captcha = RedisUtil.get(verifyKey);
        RedisUtil.del(verifyKey);
        logger.info("已从 Redis 中删除验证码，键: {}", verifyKey);
        if (captcha == null) {
            logger.error("验证码已过期，键: {}", verifyKey);
            throw new IcoolkjMSException("验证码已过期");
        }
        if (captchaDTO.getCaptcha().equalsIgnoreCase(captcha)) {
            logger.info("验证码验证成功，{}: {}", fieldName, keyField);
            return true;
        }
        logger.info("验证码验证失败，{}: {}", fieldName, keyField);
        return false;
    }
}